<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="subjectType">
        <el-radio-group @change="handleQuery" v-model="queryParams.subjectType" >
          <el-radio-button label="资产" value="ZC" />
          <el-radio-button label="负债" value="FZ" />
          <el-radio-button label="权益" value="QY" />
          <el-radio-button label="成本" value="CB" />
          <el-radio-button label="损益" value="SY" />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain size="small"
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['project:FinSubject:add']"
        >新增</el-button>
        <el-button
            type="primary"
            plain size="small"
            icon="Plus"
            @click="handleSyncSubjectMonth"
            v-hasPermi="['project:FinSubject:add']"
        >同步科目数据</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="FinSubjectList" border row-key="id" stripe >
      <el-table-column label="科目编号" align="left" prop="code" width="200"/>
      <el-table-column label="科目名称" align="left" prop="name" width="300"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button size="small" type="primary"   link icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['project:FinSubject:add']">新增</el-button>
          <el-button size="small" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['project:FinSubject:edit']">修改</el-button>
          <el-button size="small" link type="primary" v-if="!scope.row.hasDefault && scope.row.children ==undefined" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['project:FinSubject:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="subjectType" width="120">
        <template #default="scope">
          <FinSubjectType :subject-type-val="scope.row.subjectType"></FinSubjectType>
        </template>
      </el-table-column>
      <el-table-column label="借贷方向" align="center" prop="directionType"  width="150">
        <template #default="scope">
          <FinSubjectDirectionType :direction-type-val="scope.row.directionType"></FinSubjectDirectionType>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改科目对话框 -->
    <el-dialog :title="title" v-model="open" width="50%" append-to-body>
      <el-form ref="FinSubjectRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="类别" prop="subjectType">
          <el-radio-group  v-model="form.subjectType"  @change="getParentList()">
            <el-radio-button label="资产" value="ZC" />
            <el-radio-button label="负债" value="FZ" />
            <el-radio-button label="权益" value="QY" />
            <el-radio-button label="成本" value="CB" />
            <el-radio-button label="损益" value="SY" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级科目" prop="parentId">
          <el-select v-model="form.parentId"   clearable >
            <el-option  v-for="item in parentSubjectList" :key="item.id" :label="item.code+'  '+item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input type="number" v-model="form.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="方向" prop="directionType">
          <el-radio-group  v-model="form.directionType" >
            <el-radio-button label="借" value="JIE" />
            <el-radio-button label="贷" value="DAI" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="现金科目" prop="moneyType">
          <el-radio-group  v-model="form.moneyType" >
            <el-radio-button label="现金" value="MONEY" />
            <el-radio-button label="银行" value="BANK" />
            <el-radio-button label="现金等价物" value="MONEY_EQUAL" />
            <el-radio-button label="非现金科目" value="NOT_MONEY" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FinSubject">
import {
  listFinSubject,
  getFinSubject,
  delFinSubject,
  addFinSubject,
  updateFinSubject,
  syncSubjectMonth
} from "@/api/project/FinSubject";
import FinSubjectType from "@/components/enumShow/FinSubjectType.vue";
import FinSubjectDirectionType from "@/components/enumShow/FinSubjectDirectionType.vue";

const { proxy } = getCurrentInstance();

const FinSubjectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const parentSubjectList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    parentId: null,
    subjectType: 'ZC',
    status: 'ONLINE',
    code: null,
    name: null,
    packageId: null,
    createId: null,
    orderByColumn:'code',
    isAsc:'asc'
  },
  rules: {
    subjectType: [
      { required: true, message: "类型不能为空", trigger: "change" }
    ],
    code: [
      { required: true, message: "编码不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    directionType: [
      { required: true, message: "借贷方向不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询科目列表 */
function getList() {
  loading.value = true;
  listFinSubject(queryParams.value).then(response => {
    let valueMap = new Map();
    let listValue = new Array();
    response.rows.forEach(v=>{
      valueMap.set(v.id,v)
    })
    response.rows.forEach(v=>{
      if(v.parentId && v.parentId>0){
        let parentV = valueMap.get(v.parentId)
        //parentV.hasChildren = true;
        if(parentV.children==undefined){
          parentV.children = [];
        }
        parentV.children.push(v)
      }else{
        listValue.push(v)
      }
    })
    FinSubjectList.value = listValue;
    total.value = listValue.length;
    loading.value = false;
    console.log("FinSubjectList.value->",FinSubjectList.value)
  });
}

function getParentList(row){
  listFinSubject({
    pageNum: 1,
    pageSize: 1000,
    subjectType: form.value.subjectType,
  }).then(response => {
    parentSubjectList.value = response.rows;
    if(row!=undefined){
      form.value.parentId = row.id;
    }
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    parentId: null,
    parentName: null,
    subjectType: null,
    status: 'ONLINE',
    moneyType:'NOT_MONEY',
    code: null,
    name: null,
    directionType: null,
    packageId: null,
    createId: null,
    createBy: null,
    createTime: null,
    updateId: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("FinSubjectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  form.value.subjectType = queryParams.value.subjectType;
  form.value.directionType = FinSubjectList.value[0].directionType;
  open.value = true;
  title.value = "添加科目";
  getParentList(row);
}

function handleSyncSubjectMonth(){
  proxy.$modal.confirm('是否确认同步科目到科目余额？').then(function() {
    loading.value = true;
    return syncSubjectMonth();
  }).then(() => {
    loading.value = false;
    proxy.$modal.msgSuccess("同步成功");
  }).catch(() => {});
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getFinSubject(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改科目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["FinSubjectRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFinSubject(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFinSubject(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除科目编号为"' + _ids + '"的数据项？').then(function() {
    return delFinSubject(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/FinSubject/export', {
    ...queryParams.value
  }, `FinSubject_${new Date().getTime()}.xlsx`)
}

getList();
</script>
